import json

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.http import HttpResponse
from rest_framework import generics, permissions
from rest_framework.exceptions import NotAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from Login.models import User
from utils.myredis import r
from utils.storage import upload_to_cloud_storage
from .models import UserProfile
from .serializers import UserProfileSerializer
from utils.baiduapi import BaiDuApi
from utils.authentication import CustomJWTAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.parsers import JSONParser, MultiPartParser, FormParser
import base64
from rest_framework import status
from django.utils import timezone
from base.tasks import process_realname_task
import time  # 在文件顶部添加这行
from home.models import CommunityPost, Like, Friend, Interaction
from shopping.models import FavoriteRecord
from django.db.models import Q
from rest_framework.decorators import api_view, permission_classes, authentication_classes

# Create your views here.

class UserProfileDetail(generics.RetrieveUpdateAPIView):
    """返回单个用户的 UserProfile 详情"""
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer
    lookup_field = 'pk'  # 通过主键 ID 查找


class UserProfileDetailView(generics.RetrieveUpdateAPIView):
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer

    def get_object(self):
        phone = self.request.query_params.get('phone')
        if not phone:
            from rest_framework.exceptions import ValidationError
            raise ValidationError("請提供手機號")
        try:
            user = User.objects.get(phone=phone)
            return user.profile
        except User.DoesNotExist:
            from rest_framework.exceptions import NotFound
            raise NotFound("用戶不存在")
        except UserProfile.DoesNotExist:
            from rest_framework.exceptions import NotFound
            raise NotFound("該用戶沒有個人資料")


# class RealNameAuthView(APIView):
#     """
#     实名认证接口：接收身份证图片文件和用户信息，调用百度OCR，返回识别结果
#     前端需传递：image_front(文件), image_back(文件), name, id_number
#     """
#     authentication_classes = [CustomJWTAuthentication]
#     permission_classes = [IsAuthenticated]
#     parser_classes = [MultiPartParser, FormParser]
#
#     @method_decorator(csrf_exempt)
#     def post(self, request):
#         user = request.user
#         if not isinstance(user, User):
#             return Response({'code': 401, 'msg': '未登录或登录已失效'}, status=status.HTTP_401_UNAUTHORIZED)
#
#         image_front = request.FILES.get('image_front')
#         image_back = request.FILES.get('image_back')
#         name = request.data.get('name', '').strip()
#         id_number = request.data.get('id_number', '').strip()
#
#         if not all([image_front, image_back, name, id_number]):
#             return Response({'code': 400, 'msg': '参数不全'}, status=status.HTTP_400_BAD_REQUEST)
#
#         image_front_base64 = base64.b64encode(image_front.read()).decode()
#         image_back_base64 = base64.b64encode(image_back.read()).decode()
#
#         ocr = BaiDuApi()
#         ocr_result_front = ocr.idcard_ocr(image_front_base64, 'front')
#         ocr_result_back = ocr.idcard_ocr(image_back_base64, 'back')
#
#         words_result = ocr_result_front.get('words_result', {})
#         ocr_name = words_result.get('姓名', {}).get('words')
#         ocr_id = words_result.get('公民身份号码', {}).get('words')
#
#         if ocr_name == name and ocr_id == id_number:
#             profile, _ = UserProfile.objects.get_or_create(user=user)
#             profile.is_realname = True
#             profile.realname = name
#             profile.id_number = id_number
#             profile.save()
#             serializer = UserProfileSerializer(profile)
#             return Response({
#                 'code': 200,
#                 'msg': '实名认证成功',
#                 'data': serializer.data
#             })
#         else:
#             return Response({
#                 'code': 400,
#                 'msg': '实名认证失败，信息不匹配',
#                 'data': {
#                     'ocr_result_front': ocr_result_front,
#                     'ocr_result_back': ocr_result_back
#                 }
#             }, status=status.HTTP_400_BAD_REQUEST)

class RealNameAuthView(APIView):
    authentication_classes = [CustomJWTAuthentication]
    permission_classes = [IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]

    @method_decorator(csrf_exempt)
    def post(self, request):
        user = request.user
        if not isinstance(user, User):
            return Response({'code': 401, 'msg': '未登录或登录已失效'}, status=401)

        # 获取参数
        image_front = request.FILES.get('image_front')
        image_back = request.FILES.get('image_back')
        name = request.data.get('name', '').strip()
        id_number = request.data.get('id_number', '').strip()

        if not all([image_front, image_back, name, id_number]):
            return Response({'code': 400, 'msg': '参数不全'}, status=400)

        try:
            # 上传图片到云存储，获取URL
            front_url = upload_to_cloud_storage(image_front)  # 需实现
            back_url = upload_to_cloud_storage(image_back)

            # 构造任务数据
            task_data = {
                'user_id': user.id,
                'front_url': front_url,
                'back_url': back_url,
                'name': name,
                'id_number': id_number,
                'created_at': str(timezone.now())
            }

            # 存入Redis队列
            r.list_rush('realname:queue', json.dumps(task_data))

            # 触发Celery任务（可选）
            process_realname_task.delay()

            return Response({
                'code': 202,
                'msg': '实名认证已提交处理',
                'data': {
                    'task_id': f"{user.id}_{int(time.time())}",
                    'front_url': front_url,
                    'back_url': back_url
                }
            }, status=202)

        except Exception as e:
            return Response({
                'code': 500,
                'msg': f'提交实名认证失败: {str(e)}'
            }, status=500)


class UserStatsView(APIView):
    authentication_classes = [CustomJWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request, pk):
        user_id = pk
        # 动态数
        posts = CommunityPost.objects.filter(user_id=user_id).count()
        # 收藏数
        favorites = FavoriteRecord.objects.filter(user_id=user_id, is_favorited=True).count()
        # 点赞数（用户发的所有动态被点赞的总数）
        likes = Like.objects.filter(post__user_id=user_id).count()
        # 粉丝数（被关注数）
        fans = Interaction.objects.filter(target_id=user_id, type='关注').count()
        # 关注数（主动关注别人）
        follows = Interaction.objects.filter(user_id=user_id, type='关注').count()
        return Response({
            'posts': posts,
            'favorites': favorites,
            'likes': likes,
            'fans': fans,
            'follows': follows
        })


